package com.coms514.scheduleme;


import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.CheckBox;

/** 
* @author Qilin Li
* 
* */
public class AddOrEditEventActivity extends Activity {
	private String add_or_edit;
	private static int cnt;
	private ScheduleMe myState;
	//private EventInfo eventInfo = new EventInfo();
	private EventInfo eventInfo;
	
	private String notifyMethod;
	private String notifyMinutes;
	
	private TextView notifyInfo;
	private String notifyInfoString;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set_event);
		myState = ((ScheduleMe)getApplicationContext());
		eventInfo = myState.eventInfo;
		
		Intent intent = getIntent();
		add_or_edit = intent.getStringExtra("add_or_edit");
		cnt++;
		
		Spinner spinner1 = (Spinner) findViewById(R.id.repeat_rate);
		// Create an ArrayAdapter using the string array and a default spinner layout
		ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
		        R.array.repeat_rate_array, android.R.layout.simple_spinner_item);
		// Specify the layout to use when the list of choices appears
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		spinner1.setAdapter(adapter1);
		spinner1.setOnItemSelectedListener(repeatRateSelectedListener);
		
		Spinner spinner2 = (Spinner) findViewById(R.id.notify_type);
		// Create an ArrayAdapter using the string array and a default spinner layout
		ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
		        R.array.notify_method_array, android.R.layout.simple_spinner_item);
		// Specify the layout to use when the list of choices appears
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		spinner2.setAdapter(adapter2);
		spinner2.setOnItemSelectedListener(notifyTypeSelectedListener);
		
		notifyMethod = "";
		notifyMinutes = "";
		notifyInfoString = "";
		notifyInfo = (TextView) findViewById(R.id.notify_info);
		notifyInfo.setText(notifyInfoString);
		
		if (add_or_edit.compareTo("edit") == 0) {
			// Show Event contents
			ShowEventContent();
		} else {
			CheckBox checkBox1 = (CheckBox) findViewById(R.id.all_day_event);
			checkBox1.setChecked(false);
			CheckBox checkBox2 = (CheckBox) findViewById(R.id.repeat);
			checkBox2.setChecked(false);
			
			allDayEventIsTrue(checkBox1.isChecked());
			repeatingIsTrue(checkBox2.isChecked());
		}

	}
	
	private void ShowEventContent() {
		
		 EditText editText = (EditText) findViewById(R.id.set_event_title);
		 editText.setText(eventInfo.summary);
		  
		editText = (EditText) findViewById(R.id.set_event_description);
		editText.setText(eventInfo.description);
		  
		editText = (EditText) findViewById(R.id.set_event_location);
		editText.setText(eventInfo.location);
		
		CheckBox checkBox1 = (CheckBox) findViewById(R.id.all_day_event);
		checkBox1.setChecked(eventInfo.allDayEvent);
		allDayEventIsTrue(checkBox1.isChecked());
		
		CheckBox checkBox2 = (CheckBox) findViewById(R.id.repeat);
		checkBox2.setChecked(eventInfo.repeating);		
		repeatingIsTrue(checkBox2.isChecked()); 
		/* display repeat rate */
		Spinner spinner = (Spinner) findViewById(R.id.repeat_rate);
		spinner.setSelection(getRepateRatePos(eventInfo.repeatRule.getFrequence()));
		
		// update start time, end time, end repeating date
		updateButton(R.id.set_start_date);
		updateButton(R.id.set_start_time);
		updateButton(R.id.set_end_date);
		updateButton(R.id.set_end_time);
		updateButton(R.id.set_end_repeating_date);
		
	}
	
	private OnItemSelectedListener repeatRateSelectedListener = new OnItemSelectedListener() {

		@Override
		// arg0: parent, arg1: View, arg2: pos, arg3: id
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
	        // An item was selected. You can retrieve the selected item using
	        //parent.getItemAtPosition(pos)
	        String text = arg0.getItemAtPosition(arg2).toString();
	        eventInfo.repeatRule.setFrequence(getRepeatRateVal(text));
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}
	};
	
	private OnItemSelectedListener notifyTypeSelectedListener = new OnItemSelectedListener() {

		@Override
		// arg0: parent, arg1: View, arg2: pos, arg3: id
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
	        // An item was selected. You can retrieve the selected item using
	        //parent.getItemAtPosition(pos)
	        String text = arg0.getItemAtPosition(arg2).toString();
			if (text.compareTo("popup") == 0)
				notifyMethod = "popup";
			else if (text.compareTo("email") == 0)
				notifyMethod = "email";
			else if (text.compareTo("sms") == 0)
				notifyMethod = "sms";
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
	};
	
	private void allDayEventIsTrue(boolean flag) {
		Button button1 = (Button) findViewById(R.id.set_start_time);
		Button button2 = (Button) findViewById(R.id.set_end_time);
		
		if (flag == true) { // all day event
			button1.setEnabled(false);
			button2.setEnabled(false);
			 eventInfo.allDayEvent = true; 
		} else {
			button1.setEnabled(true);
			button2.setEnabled(true);
			eventInfo.allDayEvent = false;
		}
	}
	
	private String getRepeatRateVal(String text) {
		if (text.compareTo("Daily") == 0)
			return "DAILY";
		else if (text.compareTo("Weekly") == 0)
			return "WEEKLY";
		else if (text.compareTo("Monthly") == 0)
			return "MONTHLY";
		else if (text.compareTo("Yearly") == 0)
			return "YEARLY";
		else
			return null;
	}
	
	private int getRepateRatePos(String Val) {
		if (Val.compareTo("DAILY") == 0)
			return 0;
		else if (Val.compareTo("WEEKLY") == 0)
			return 1;
		else if (Val.compareTo("MONTHLY") == 0)
			return 2;
		else if (Val.compareTo("YEARLY") == 0)
			return 3;
		else
			return 0;
	}
	
	private void repeatingIsTrue(boolean flag) {
		Spinner repeateRate = (Spinner) findViewById(R.id.repeat_rate);
		Button untilDate = (Button) findViewById(R.id.set_end_repeating_date);
		
		if (flag == true) {
			repeateRate.setEnabled(true);
			untilDate.setEnabled(true);
			eventInfo.repeating = true;			

		} else {
			repeateRate.setEnabled(false);
			untilDate.setEnabled(false);
			eventInfo.repeating = false;
		}
	}

	public void onCheckboxClicked(View view) {
	    // Is the view now checked?
	    boolean checked = ((CheckBox) view).isChecked();
		Button button1 = (Button) findViewById(R.id.set_start_time);
		Button button2 = (Button) findViewById(R.id.set_end_time);
		Button button3 = (Button) findViewById(R.id.set_end_repeating_date);
		
	    // Check which checkbox was clicked
	    switch(view.getId()) {
	        case R.id.all_day_event:
	        	allDayEventIsTrue(checked);
	        	if(!checked) {
	        		button1.setText("start time");
	        		button2.setText("end time");
	        	}
	            break;
	        case R.id.repeat:
	        	repeatingIsTrue(checked);
	        	if(checked) {
	        		button3.setText("until date");
	        	}
	            break;
	    }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.set_event, menu);
		return true;
	}
	
	void updateButton(int buttonId) {
		Button button = (Button) findViewById(buttonId);
		switch (buttonId) {
		case R.id.set_start_date:
			button.setText(eventInfo.startDate.dateString);
			break;
		case R.id.set_start_time:
			button.setText(eventInfo.startTime.timeString);
			break;
		case R.id.set_end_date:
			button.setText(eventInfo.endDate.dateString);
			break;
		case R.id.set_end_time:
			button.setText(eventInfo.endTime.timeString);
			break;
		case R.id.set_end_repeating_date:
			button.setText(eventInfo.repeatRule.endDate);
			break;
		default:
			break;
		}
	}
	
	 	private DatePickerDialog.OnDateSetListener startDateListener = 
	            new DatePickerDialog.OnDateSetListener() {  

			/*
			arg0: The view associated with this listener.  
			arg1: The year that was set. 
			arg2: The month that was set (0-11) for compatibility with Calendar. 
			arg3: The day of the month that was set.  
			*/
	        @Override
	        public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
	        	eventInfo.startDate.setDate(arg1, arg2 + 1, arg3);
	        	updateButton(R.id.set_start_date);
	        }

	    }; 
	    
	    private TimePickerDialog.OnTimeSetListener startTimeListener =
	            new TimePickerDialog.OnTimeSetListener() {

	                @Override
	                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	                	eventInfo.startTime.setTime(hourOfDay, minute);
	                	updateButton(R.id.set_start_time);
	                }
	            };


	 	private DatePickerDialog.OnDateSetListener endDateListener = 
	            new DatePickerDialog.OnDateSetListener() {  

	        @Override
	        public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
	        	eventInfo.endDate.setDate(arg1, arg2 + 1, arg3);
	        	updateButton(R.id.set_end_date);
	        }

	    };
	    
	    private TimePickerDialog.OnTimeSetListener endTimeListener =
	            new TimePickerDialog.OnTimeSetListener() {

	                @Override
	                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
	                	eventInfo.endTime.setTime(hourOfDay, minute);
	                	updateButton(R.id.set_end_time);
	                }
	            };
	            
	 	private DatePickerDialog.OnDateSetListener endRepeatingDateListener = 
	            new DatePickerDialog.OnDateSetListener() {  

	        @Override
	        public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
	        	eventInfo.repeatRule.setEndDateTime(arg1, arg2 + 1, arg3);
	        	updateButton(R.id.set_end_repeating_date);
	        }

	    };
	
	public void onClickButton(View view) {
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        
		switch (view.getId()) {

		case R.id.set_start_date:
			// FIXME: pass current date
			 new DatePickerDialog(this, startDateListener,
					 year, month, day).show();
			break;
		case R.id.set_start_time:
			new TimePickerDialog(this, startTimeListener, 
                    hour, minute, true).show();
			break;
		case R.id.set_end_date:
			 new DatePickerDialog(this, endDateListener,
	                    year, month, day).show();  
			break;
		case R.id.set_end_time:
			new TimePickerDialog(this, endTimeListener, 
                    hour, minute, true).show();
			break;
		case R.id.set_end_repeating_date:
			new DatePickerDialog(this, endRepeatingDateListener, 
					year, month, day).show();
			break;
		case R.id.add_notification:
			
			EditText minutes = (EditText) findViewById(R.id.notify_minutes);
			notifyMinutes = minutes.getText().toString();
			
			notifyInfoString = notifyInfoString + notifyMethod + ": " + notifyMinutes + " minutes\n";
			Log.v("myTest", "Notify: " + notifyInfoString);
			notifyInfo.setText(notifyInfoString);
			eventInfo.addReminder(notifyMethod, Integer.parseInt(notifyMinutes));
			break;
		default:
			break;
		}
	}
	
	  public void onSave(View view) {
			 /* Create a new event */
		      Intent t = new Intent();
		      EditText editText = (EditText) findViewById(R.id.set_event_title);
		      eventInfo.summary = editText.getText().toString();
		      
		      editText = (EditText) findViewById(R.id.set_event_description);
		      eventInfo.description =  editText.getText().toString();
		      
		      editText = (EditText) findViewById(R.id.set_event_location);
		      eventInfo.location = editText.getText().toString();

		      eventInfo.color = "3";
		      
		      myState.eventInfo = eventInfo;
		      setResult(Activity.RESULT_OK, t); 
		      
		      finish();
		  }

		  public void onCancel(View view) {
		    setResult(Activity.RESULT_CANCELED);
		    finish();
		  }

}
